package com.demo.lab.controller;

import com.demo.lab.entity.base.Result;
import com.demo.lab.config.Constant;
import com.demo.lab.entity.User;
import com.demo.lab.service.UserService;
import com.demo.lab.utils.TimeUtils;
import com.demo.lab.utils.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/")
public class LoginController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    public static final String CAPTCHA_KEY = "session_captcha";

    @Autowired
    UserService userService;

    /*
     * @Description:  跳转登陆页面
     * @Param:
     * @return:  login
     */
    @GetMapping("/")
    public ModelAndView login() {
        return jumpPage("login");
    }

    @GetMapping("login")
    public ModelAndView login2() {
        return jumpPage("login");
    }

    /*
     * @Description: 获取验证码
     * @Param:  request response session
     * @return:  将验证码存入session
     */
    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 生成图片
        int w = 130, h = 48;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
        // 将验证码存储在session以便登录时校验
        session.setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());
    }

    /*
     * @Description: 登陆操作
     * @Param:  用户实体类
     * @return:
     */
    @PostMapping(value = "login")
    @ResponseBody
    public Result loginSystem(@RequestBody User user, HttpSession session) {

        //验证是否为空
        if (user.getUserpwd() == null || user.getUsername() == null || user.getCaptcha() == null) {
            return Result.failure(400, Constant.LOGIN_FAIL);
        }
        String captcha = (String) session.getAttribute(CAPTCHA_KEY);
        //判断验证码是否正确
        if (captcha.equals(user.getCaptcha().toLowerCase())) {
            //判断用户是否冻结
            if (userService.checkUserLock(user.getUsername())) {
                //判断用户密码
                if (userService.checkUserPwd(user)) {
                    //获取用户信息
                    User userinfo = userService.findOne(user.getUsername());
                    session.setAttribute("user", userinfo);
                    session.setAttribute("userId", userinfo.getId());
                    session.setAttribute("username", userinfo.getUsername());
                    //更新最后登录时间
                    userinfo.setLastLoginTime(TimeUtils.getTime());
                    userService.update(userinfo);
                    return Result.success(200, Constant.LOGIN_SUCCESS);
                }
            } else {
                return Result.failure(400, Constant.USER_LOCK);
            }
        } else {
            return Result.failure(400, Constant.CAPTCHA_FAIL);
        }
        return Result.failure(400, Constant.LOGIN_ERROR);
    }

    @GetMapping("logout")
    public ModelAndView add(HttpSession session) {
        session.removeAttribute("user");
        ModelAndView md = new ModelAndView();
        md.setViewName("login");
        return md;
    }

}
